package com.lik888.justauth_demo.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lik888.justauth_demo.Context.Client;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/auth")
public class RestAuthController {
    @Autowired
    private Client client;

    // 1. 发起授权：生成 state 并存到 Session
    @RequestMapping("/reader")
    public void readerAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成随机 state
        String state = AuthStateUtils.createState();
        // 把 state 存到当前用户的 Session 中（key 用 "AUTH_STATE" 方便后续取出）
        request.getSession().setAttribute("AUTH_STATE", state);
        // 发起授权，传入存好的 state
        AuthRequest authRequest = getAuthRequest();
        String authorizeUrl = authRequest.authorize(state);
        // 重定向到 Gitee 登录页
        response.sendRedirect(authorizeUrl);
    }

    // 2. 回调：从 Session 取 state 并验证
    @RequestMapping("/callback")
    public Object callback(HttpServletRequest request, AuthCallback authCallback) throws Exception {
        // 从 Session 中取出之前存的 state
        String savedState = (String) request.getSession().getAttribute("AUTH_STATE");
        // 从 Gitee 回调参数中取出返回的 state
        String callbackState = authCallback.getState();

        // 手动验证 state：如果不匹配，直接抛异常
        if (savedState == null || !savedState.equals(callbackState)) {
            throw new RuntimeException("Illegal state: 可能存在 CSRF 攻击风险");
        }

        // state 验证通过后，再执行登录逻辑
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> login = authRequest.login(authCallback);
        String username = login.getData().getUsername();
        // 登录完成后，删除 Session 中的 state（避免重复使用）
        request.getSession().removeAttribute("AUTH_STATE");

        System.out.println(username);
        return login;
    }

    // 初始化 AuthRequest（不变）
    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId(client.getClientId())
                .clientSecret(client.getClientSecret())
                .redirectUri(client.getRedirectUri())
                .build());
    }
}